package ui;

import java.awt.Color;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Collection;
import java.util.Timer;
import java.util.Vector;

import javax.swing.JOptionPane;

import core.Client;
import core.Global;
import core.MinaServer;
import core.MinaSocket;
import core.MyTask;
import sound.SoundPlay;
import util.ServerCache;
import util.UserData;

import javax.swing.DropMode;
import javax.swing.JList;

import org.apache.mina.core.session.IoSession;




import javax.swing.JButton;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

import javax.swing.GroupLayout.Alignment;
import javax.swing.GroupLayout;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JLabel;

/**
 * 
 * @author 胡海亮  QQ:249782944
 * 学校:中南大学 商学院
 * EnterpriseIMServer :企业即时通讯
 * Apr 27, 2010
 */
public class ServerMainFrame extends BaseFrame implements Runnable{

	private static final long serialVersionUID = 1L;
	private static ServerMainFrame instance;
	private MinaServer  server;
	public static ServerMainFrame getInstance(){
		if(instance==null){
			instance=new ServerMainFrame();
		}
		return instance;
	}
	private ServerMainFrame() {
		super();
		initComponents();
	}

	private void initComponents() {
		//系统菜单：关于 退出
		menuBar = new javax.swing.JMenuBar();
		sysMenu = new javax.swing.JMenu();
		configMenu = new javax.swing.JMenu();
		
		aboutMenuItem = new javax.swing.JMenuItem();
		jSeparator1 = new javax.swing.JSeparator();
		exitMenuItem = new javax.swing.JMenuItem();

		serverConfigMenuItem = new javax.swing.JMenuItem();
		jSeparator2 = new javax.swing.JSeparator();
		clientConfigMenuItem = new javax.swing.JMenuItem();

		settingsConfigMenuItem = new javax.swing.JMenuItem();
		jSeparator3 = new javax.swing.JSeparator();
		settingsConfigMenuItem = new javax.swing.JMenuItem();
		
		leftPanel = new javax.swing.JPanel();
		//propetryTree = PropetryTree.getInstance(EIMDesktop.getInstance().getDeskTopConfig());
		//chartPanel = new MemoryMonitor();
		//cupPanel = new CPUMonitor();


		shangPanel = new javax.swing.JPanel();
		jToolBar1 = new javax.swing.JToolBar();
		jToolBar1.setEnabled(false);
		startButton = new javax.swing.JButton();
		stopButton = new javax.swing.JButton();
		//stopButton.setEnabled(false);
		//refreshButton.setEnabled(false);

		jLabel1 = new javax.swing.JLabel();
		jLabel2 = new javax.swing.JLabel();

		//desktopPane = EIMDesktop.getInstance();
		cmdScrollPane = new javax.swing.JScrollPane();

		btnBoardCast = new JButton("群发");
		btnBoardCast.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String title = (String)JOptionPane.showInputDialog(null,"请输入发送信息：\n","输入",JOptionPane.PLAIN_MESSAGE,null,null,"在这输入");
				Timer timer = new Timer();
				timer.schedule(new MyTask(title), 1000);//在1秒后执行此任务,每次间隔5秒,如果传递一个Data参数,就可以在某个固定的时间执行这个任务.
			}
		});
		leftPanel.add(btnBoardCast);


		userList = new JList();

		JLabel label = new JLabel("在线列表：");
		
		JButton button_1 = new JButton("更新版本");
		button_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
					String title = (String)JOptionPane.showInputDialog(null,"请输入版本号：\n","输入",JOptionPane.PLAIN_MESSAGE,null,null,"例：1.0");
					Global.getInstance().setUpdateVersion_android(title);
			}
		});

		javax.swing.GroupLayout leftPanelLayout = new javax.swing.GroupLayout(leftPanel);
		leftPanelLayout.setHorizontalGroup(
			leftPanelLayout.createParallelGroup(Alignment.LEADING)
				.addGroup(leftPanelLayout.createSequentialGroup()
					.addContainerGap()
					.addGroup(leftPanelLayout.createParallelGroup(Alignment.LEADING)
						.addComponent(userList, GroupLayout.DEFAULT_SIZE, 177, Short.MAX_VALUE)
						.addComponent(label)
						.addGroup(Alignment.TRAILING, leftPanelLayout.createSequentialGroup()
							.addComponent(button_1)
							.addPreferredGap(ComponentPlacement.RELATED, 25, Short.MAX_VALUE)
							.addComponent(btnBoardCast, GroupLayout.PREFERRED_SIZE, 71, GroupLayout.PREFERRED_SIZE)))
					.addContainerGap())
		);
		leftPanelLayout.setVerticalGroup(
			leftPanelLayout.createParallelGroup(Alignment.LEADING)
				.addGroup(leftPanelLayout.createSequentialGroup()
					.addGap(14)
					.addComponent(label)
					.addGap(18)
					.addComponent(userList, GroupLayout.PREFERRED_SIZE, 443, GroupLayout.PREFERRED_SIZE)
					.addPreferredGap(ComponentPlacement.UNRELATED)
					.addGroup(leftPanelLayout.createParallelGroup(Alignment.BASELINE)
						.addComponent(button_1, GroupLayout.PREFERRED_SIZE, 27, GroupLayout.PREFERRED_SIZE)
						.addComponent(btnBoardCast, GroupLayout.DEFAULT_SIZE, 31, Short.MAX_VALUE))
					.addGap(47))
		);


		leftPanel.setLayout(leftPanelLayout);

		//startButton.setIcon(ResourseMannager.getIconUrlByName("start.png"));

		startButton.setText("\u542f\u52a8\u670d\u52a1");
		startButton.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mouseClicked(java.awt.event.MouseEvent evt) {
				startButtonMouseClicked(evt);
			}
		});

		jToolBar1.add(startButton);

		// stopButton.setIcon(ResourseMannager.getIconUrlByName("stop.png"));
		stopButton.setText("\u505c\u6b62\u670d\u52a1");
		stopButton.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mouseClicked(java.awt.event.MouseEvent evt) {
				stopButtonMouseClicked(evt);
			}
		});

		jToolBar1.add(stopButton);

		jLabel1.setText("\u5728\u7ebf\u4eba\u6570:");
		jToolBar1.add(jLabel1);

		jLabel2.setText("0");
		jToolBar1.add(jLabel2);

		javax.swing.GroupLayout shangPanelLayout = new javax.swing.GroupLayout(shangPanel);
		shangPanelLayout.setHorizontalGroup(
				shangPanelLayout.createParallelGroup(Alignment.LEADING)
				.addComponent(jToolBar1, GroupLayout.DEFAULT_SIZE, 784, Short.MAX_VALUE)
				);
		shangPanelLayout.setVerticalGroup(
				shangPanelLayout.createParallelGroup(Alignment.LEADING)
				.addGroup(shangPanelLayout.createSequentialGroup()
						.addComponent(jToolBar1, GroupLayout.PREFERRED_SIZE, 47, GroupLayout.PREFERRED_SIZE)
						.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
				);
		
		label_2 = new JLabel();
		label_2.setText("上位机状态:");
		jToolBar1.add(label_2);
		
		label_pcState = new JLabel();
		label_pcState.setText("异常");
		jToolBar1.add(label_pcState);
		shangPanel.setLayout(shangPanelLayout);


		//最上面的菜单
		sysMenu.setText("\u7cfb\u7edf");
		aboutMenuItem.setText("\u5173\u4e8e\u7cfb\u7edf");
		sysMenu.add(aboutMenuItem);

		sysMenu.add(jSeparator1);
		
		exitMenuItem.setText("\u9000\u51fa\u7cfb\u7edf");
		exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				exitMenuItemActionPerformed(evt);
			}
		});

		sysMenu.add(exitMenuItem);

		configMenu.setText("配置信息");
		serverConfigMenuItem.setText("服务器配置");
		serverConfigMenuItem.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				//PropertyFrame propertyFrame=PropertyFrame.getInstance();
				PropertyFrame propertyFrame=new PropertyFrame(1);
				//remove(propertyFrame);
				//repaint();
				//add(propertyFrame);
				propertyFrame.show();
			}
		});
		configMenu.add(serverConfigMenuItem);
		configMenu.add(jSeparator2);
		clientConfigMenuItem.setText("客户端配置");
		clientConfigMenuItem.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				
				//PropertyFrame propertyFrame=PropertyFrame.getInstance();
				PropertyFrame propertyFrame=new PropertyFrame(2);
				//remove(propertyFrame);
				//repaint();
				//add(propertyFrame);
				propertyFrame.show();
			}
		});
		configMenu.add(clientConfigMenuItem);
		
		configMenu.add(settingsConfigMenuItem);
		configMenu.add(jSeparator3);
		settingsConfigMenuItem.setText("软件配置");
		settingsConfigMenuItem.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				
				//PropertyFrame propertyFrame=PropertyFrame.getInstance();
				PropertyFrame propertyFrame=new PropertyFrame(3);
				//remove(propertyFrame);
				//repaint();
				//add(propertyFrame);
				propertyFrame.show();
			}
		});
		configMenu.add(settingsConfigMenuItem);
		
		menuBar.add(sysMenu);
		menuBar.add(configMenu);
		setJMenuBar(menuBar);

		label_1 = new JLabel("事件记录：");

		JButton button = new JButton("清空");
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				clearCMDInfo();
			}
		});




		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
		layout.setHorizontalGroup(
			layout.createParallelGroup(Alignment.LEADING)
				.addGroup(layout.createSequentialGroup()
					.addComponent(leftPanel, GroupLayout.PREFERRED_SIZE, 197, GroupLayout.PREFERRED_SIZE)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addGroup(layout.createParallelGroup(Alignment.TRAILING)
						.addGroup(layout.createParallelGroup(Alignment.LEADING)
							.addComponent(label_1, GroupLayout.PREFERRED_SIZE, 77, GroupLayout.PREFERRED_SIZE)
							.addComponent(cmdScrollPane, GroupLayout.PREFERRED_SIZE, 609, GroupLayout.PREFERRED_SIZE))
						.addComponent(button, GroupLayout.PREFERRED_SIZE, 71, GroupLayout.PREFERRED_SIZE))
					.addContainerGap())
				.addComponent(shangPanel, GroupLayout.DEFAULT_SIZE, 828, Short.MAX_VALUE)
		);
		layout.setVerticalGroup(
			layout.createParallelGroup(Alignment.LEADING)
				.addGroup(layout.createSequentialGroup()
					.addComponent(shangPanel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
					.addGroup(layout.createParallelGroup(Alignment.LEADING)
						.addGroup(layout.createSequentialGroup()
							.addGap(21)
							.addComponent(label_1)
							.addGap(18)
							.addComponent(cmdScrollPane, GroupLayout.PREFERRED_SIZE, 443, GroupLayout.PREFERRED_SIZE)
							.addPreferredGap(ComponentPlacement.RELATED)
							.addComponent(button, GroupLayout.PREFERRED_SIZE, 31, GroupLayout.PREFERRED_SIZE)
							.addGap(50))
						.addGroup(layout.createSequentialGroup()
							.addPreferredGap(ComponentPlacement.RELATED)
							.addComponent(leftPanel, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
		);
		CMDPane = new InfoTextPanel();
		cmdScrollPane.setViewportView(CMDPane);
		getContentPane().setLayout(layout);


		addWindowListener(new WindowAdapter(){
			public void windowClosing(WindowEvent e){
				setVisible(false);
			}});

		this.setSize(844, 700);
	}

	public void run() {
		ServerMainFrame serverMainFrame=ServerMainFrame.getInstance();
		BaseFrame.centerWindow(serverMainFrame);
		serverMainFrame.setVisible(true);
	}

	private void stopButtonMouseClicked(java.awt.event.MouseEvent evt) {
		int sure=getOptionDialog("关闭服务器?");
		if(sure==0){
			server=MinaServer.getInstance();
			boolean re=server.closeServer();

			if(true)
			{
				stopButton.setEnabled(false);
				startButton.setEnabled(true);
				ServerTrayIcon.getInstanse().changeIconIamge("closed");
				ToolTip.startBubbleTip("远程能源管理系统服务器已经关闭了");

			}else{
				javax.swing.JOptionPane.showMessageDialog(this,"服务器已经关闭,不能关闭两次");
			}

		}
	}

	private void startButtonMouseClicked(java.awt.event.MouseEvent evt) {
		int sure=getOptionDialog("开启服务器");

		if(sure==0){

			server=MinaServer.getInstance();
			boolean re=server.startServer();
			if(re){
				stopButton.setEnabled(true);
				startButton.setEnabled(false);
				ServerTrayIcon.getInstanse().changeIconIamge("start");
				ToolTip.startBubbleTip("远程能源管理系统服务器成功开启");
			}else{
				javax.swing.JOptionPane.showMessageDialog(this,"服务器已经启动,不能启动两次");
			}
		}

	}

	private int getOptionDialog(String msg){
		Object[] options = {"确定?","取消?"};
		int response=JOptionPane.showOptionDialog ( this, "您确定"+msg,msg,JOptionPane.YES_OPTION ,JOptionPane.PLAIN_MESSAGE,
				null, options, options[0] );
		return response;
	}

	private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
		int sure=getOptionDialog("退出并关闭服务器？");
		if(sure==0){
			SoundPlay.playClosedSound();
			System.exit(3);
		}
	}

	public void addCMDInfo(String info){
		String cmd=CMDPane.getText();
		cmd=cmd+info;
		CMDPane.setText(cmd);
		CMDPane.setCaretPosition(CMDPane.getDocument().getLength());
	}
	
	public void clearCMDInfo(){
		CMDPane.setText("");
		CMDPane.setCaretPosition(CMDPane.getDocument().getLength());
	}


	// 变量声明 - 不进行修改//GEN-BEGIN:variables
	private InfoTextPanel CMDPane;
	//菜单
	private javax.swing.JMenu sysMenu;
	private javax.swing.JMenu configMenu;
	
	
	private javax.swing.JMenuBar menuBar;
	private javax.swing.JMenuItem aboutMenuItem;
	private javax.swing.JSeparator jSeparator1;
	private javax.swing.JMenuItem exitMenuItem;
	
	private javax.swing.JMenuItem serverConfigMenuItem;
	private javax.swing.JSeparator jSeparator2;
	private javax.swing.JMenuItem clientConfigMenuItem;
	private javax.swing.JSeparator jSeparator3;
	private javax.swing.JMenuItem settingsConfigMenuItem;
	
	
	private javax.swing.JScrollPane cmdScrollPane;


	private javax.swing.JPanel leftPanel;

	//最上面的按钮
	private javax.swing.JToolBar jToolBar1;
	private javax.swing.JPanel shangPanel;
	private javax.swing.JButton startButton;
	private javax.swing.JButton stopButton;
	private javax.swing.JLabel jLabel1;
	private javax.swing.JLabel jLabel2;
	private JList userList;
	private JButton btnBoardCast;
	private JLabel label_1;
	private JLabel label_2;
	private JLabel label_pcState;
	// 变量声明结束//GEN-END:variables
	public void updataOnlineNum()
	{
		ServerCache serverCache = ServerCache.getInstance();
		MinaSocket minaSocket = MinaSocket.getInstance();
		serverCache.setOnlineNum(minaSocket.serverCount());
		jLabel2.setText(Integer.toString(serverCache.getOnlineNum()));
	}
	public void updataOnlineUser()
	{
		/*
		Vector vt=new Vector();
		Collection<IoSession> sessions = ServerCache.getInstance().getUserConnectMap().values();//从主线程中取得session  
		for (IoSession sess : sessions) {  
			if (sess.isConnected()) {  
				vt.add(sess.);
			}else
			{
				vt.add(sess.);
			}  
		}
		userList.setListData(vt);
		 */
		/*
		Vector vt=new Vector();
		Collection<UserData> users = ServerCache.getInstance().getOnLineUserMap().values();//从主线程中取得session  
		for (UserData user : users) {  
			vt.add(user.getIp());
				
		}
		userList.setListData(vt);
		*/
		
		Vector vt=new Vector();
		Collection<String> users = ServerCache.getInstance().getIdMap().values();//从主线程中取得session  
		for (String user : users) {
			vt.add(user);
				
		}
		userList.setListData(vt);
	}
	public void updataPcNetState(boolean isOk)
	{
		if(isOk)
		{
			label_pcState.setText("正常");
		}else
		{
			label_pcState.setText("异常");
			ToolTip.startBubbleTip("服务器发生异常！");
		}
	}
}
